﻿using LightCAD.Core;
using LightCAD.Drawing.Actions;
using LightCAD.Runtime;
using LightCAD.Runtime.Interface;
using LightCAD.UI.Layer;
using LightCAD.UI.LineType;
//using netDxf;
using SixLabors.ImageSharp.ColorSpaces;
using Svg;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reactive;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace LightCAD.UI
{
    public partial class LayerManageWindow : FormBase, ILayerManageWindow
    {
        private LayerManageAction layerManageAction;
        public static event EventHandler<LcDocument> LayerChanged;
        public string CurrentAction { get; set; }
        public bool IsActive => true;
        public Type WinType => this.GetType();
        private string layerName;
        public LayerManageWindow()
        {
            InitializeComponent();

        }

        public LayerManageWindow(params object[] args) : this()
        {
            if (args != null && args.Length > 0)
            {
                this.layerManageAction = (LayerManageAction)args[0];
                this.CurrentAction = "OK";
            }
        }

        private void SetColorImage()
        {
            foreach (DataGridViewRow row in dgvLayerList.Rows)
            {
                Bitmap bmp = new Bitmap(20, 20);
                Graphics g = Graphics.FromImage(bmp);
                UInt32 uintValue = Convert.ToUInt32(row.Cells[6].Value.ToString());
                SolidBrush b = new SolidBrush(GetColorByUint(uintValue));//这里修改颜色
                g.FillRectangle(b, 0, 0, 20, 20);
                System.Drawing.Rectangle rec = new Rectangle(1, 1, 20, 20);
                g.DrawRectangle(new Pen(System.Drawing.Color.Black, 1), 0, 0, 19, 19);
                row.Cells[5].Value = bmp;
            }
        }

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex > -1 && e.ColumnIndex > -1)
            {
                if (dgvLayerList.Columns[e.ColumnIndex].Name == "name")
                {
                    layerName = dgvLayerList.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
                }
                if (dgvLayerList.Columns[e.ColumnIndex].Name == "IsOpen")
                {
                    if (dgvLayerList.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString() == "False")
                        dgvLayerList.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = true;
                    else
                        dgvLayerList.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = false;
                    //foreach (var item in this.layerManageAction.vportRt.ActiveElementSet.Elements)
                    //{
                    //    if (item.Layer == dgvLayerList.Rows[e.RowIndex].Cells[1].Value.ToString())
                    //    {
                    //        item.Visible = (bool)dgvLayerList.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
                    //    }
                    //}
                }
                if (dgvLayerList.Columns[e.ColumnIndex].Name == "IsFrozen")
                {
                    if (dgvLayerList.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString() == "False")
                        dgvLayerList.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = true;
                    else
                        dgvLayerList.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = false;
                    //foreach (var item in this.layerManageAction.vportRt.ActiveElementSet.Elements)
                    //{
                    //    if (item.Layer == dgvLayerList.Rows[e.RowIndex].Cells[1].Value.ToString())
                    //    {
                    //        item.Visible = (bool)dgvLayerList.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
                    //    }
                    //}
                }
                if (dgvLayerList.Columns[e.ColumnIndex].Name == "IsLock")
                {
                    if (dgvLayerList.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString() == "False")
                        dgvLayerList.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = true;
                    else
                        dgvLayerList.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = false;
                    //foreach (var item in this.layerManageAction.vportRt.ActiveElementSet.Elements)
                    //{
                    //    if (item.Layer == dgvLayerList.Rows[e.RowIndex].Cells[1].Value.ToString())
                    //    {
                    //        item.Visible = (bool)dgvLayerList.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
                    //    }
                    //}
                }
                if (dgvLayerList.Columns[e.ColumnIndex].Name == "Color")
                {
                    ColorDialog colorDialog = new ColorDialog();
                    UInt32 uintValue = Convert.ToUInt32(dgvLayerList.Rows[e.RowIndex].Cells[6].Value.ToString());
                    colorDialog.Color = GetColorByUint(uintValue);

                    if (colorDialog.ShowDialog() == DialogResult.OK)
                    {
                        int rgbm = colorDialog.Color.ToArgb();
                        //Color.FromArgb((byte)this.mTrueColor, (byte)(((short)this.mTrueColor) >> 8), (byte)(this.mTrueColor >> 0x10));

                        //dgvLayerList.Rows[e.RowIndex].Cells[6].Value = (uint)(((uint)colorDialog.Color.B << 24) | (ushort)(((ushort)colorDialog.Color.G << 16) |  colorDialog.Color.R));

                        dgvLayerList.Rows[e.RowIndex].Cells[6].Value = RGBFromSystem(colorDialog.Color);
                        //System.Drawing.Color.FromArgb((byte)((rgbm >> 24) & 255), (ushort)((rgbm >> 16) & 255), (ushort)((rgbm >> 8) & 255), (ushort)(rgbm & 255))
                        SetColorImage();

                        //foreach (var item in this.layerManageAction.vportRt.ActiveElementSet.Elements)
                        //{
                        //    if (item.Layer == dgvLayerList.Rows[e.RowIndex].Cells[1].Value.ToString())
                        //    {
                        //        item.Color = dgvLayerList.Rows[e.RowIndex].Cells[6].Value.ToString();
                        //    }
                        //}

                    }
                }
                if (dgvLayerList.Columns[e.ColumnIndex].Name == "LineWidth")
                {
                    LineWidthWindow lineWidthWindow = new LineWidthWindow((LineWeight)dgvLayerList.Rows[e.RowIndex].Cells["LineWidth"].Value);
                    if (lineWidthWindow.ShowDialog() == DialogResult.OK)
                    {
                        dgvLayerList.Rows[e.RowIndex].Cells["LineWidth"].Value = lineWidthWindow.SelectLineWidth;
                    }
                }
                if (dgvLayerList.Columns[e.ColumnIndex].Name == "LineType")
                {
                    LineTypeWindow LinetypeForm = new LineTypeWindow(layerManageAction.lcDocument, dgvLayerList.Rows[e.RowIndex].Cells["LineType"].Value?.ToString());
                    if (LinetypeForm.ShowDialog() == DialogResult.OK)
                    {
                        LcLineType selectlinetype = LinetypeForm.LineType;
                        dgvLayerList.Rows[e.RowIndex].Cells["LineType"].Value = selectlinetype.LineTypeName;
                        foreach (var item in this.layerManageAction.vportRt.ActiveElementSet.Elements)
                        {
                            if (item.Layer == dgvLayerList.Rows[e.RowIndex].Cells[1].Value.ToString())
                            {
                                item.LineType = dgvLayerList.Rows[e.RowIndex].Cells["LineType"].Value.ToString();
                            }
                        }
                    }
                }
                if (dgvLayerList.Columns[e.ColumnIndex].Name == "Transparency")
                {
                    double transparency = Convert.ToDouble(dgvLayerList.Rows[e.RowIndex].Cells["Transparency"].Value);
                    TransparencyWindow transparencyWindow = new TransparencyWindow(layerManageAction, transparency, dgvLayerList.Rows[e.RowIndex].Cells["name"].Value?.ToString());
                    if (transparencyWindow.ShowDialog() == DialogResult.OK)
                    {
                    }
                }
                //MessageBox.Show(dgvLayerList.Columns[e.ColumnIndex].HeaderText);
            }
        }
        //Color转Uint
        public static uint RGBFromSystem(Color color)
        {
            return (uint)(color.A << 24 | (color.R << 16) | (color.G << 8) | (color.B));
        }
        //Uint转Color
        private Color GetColorByUint(uint uintValue)
        {
            Color colorConverted = System.Drawing.Color.FromArgb((byte)((uintValue >> 24) & 255), (ushort)((uintValue >> 16) & 255), (ushort)((uintValue >> 8) & 255), (ushort)(uintValue & 255));
            return colorConverted;
        }
        public void InitLayers()
        {
            this.dgvLayerList.DataSource = null;
            this.dgvLayerList.AutoGenerateColumns = false;
            this.dgvLayerList.DataSource = layerManageAction.lcDocument.Layers;
            //if (layerManageAction.lcDocument.Layers.Where(x => x.IsStatus == true).FirstOrDefault() == null)
            //    layerManageAction.lcDocument.Layers.Where(x => x.Name == "0").FirstOrDefault().IsStatus = true;
            SetColorImage();
        }

        private void LayerManageWindow_Load(object sender, EventArgs e)
        {
            InitLayers();
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            //int index = this.dgvLayerList.Rows.GetLastRow(DataGridViewElementStates.Visible) + 1;
            //int index = this.dgvLayerList.Rows.Add();
            LcLayer lcLayer = layerManageAction.lcDocument.CreateObject<LcLayer>();
            lcLayer.IsStatus = false;
            lcLayer.Name = "图层" + layerManageAction.lcDocument.Layers.Count;
            lcLayer.IsOff = false;
            lcLayer.IsFrozen = false;
            lcLayer.IsLocked = false;
            lcLayer.Color = 0xFF00FF00;
            lcLayer.LineTypeId = 1;
            lcLayer.LineWeight = LineWeight.ByLayer;
            lcLayer.Transparency = 0;
            lcLayer.ViewportVisibilityDefault = 0;
            lcLayer.IsPlottable = true;
            lcLayer.Description = "";
            lcLayer.LineTypeName = "BYLAYER";
            layerManageAction.lcDocument.Layers.Add(lcLayer);
            InitLayers();
            LayerChanged?.Invoke(this, layerManageAction.lcDocument);

            //this.dgvLayerList.Rows[index].Cells[0].Value = "";
            //this.dgvLayerList.Rows[index].Cells[1].Value = "图层"+index;
            //this.dgvLayerList.Rows[index].Cells[2].Value = false;
            //this.dgvLayerList.Rows[index].Cells[3].Value = false;
            //this.dgvLayerList.Rows[index].Cells[4].Value = false;
            //this.dgvLayerList.Rows[index].Cells[5].Value = 0xFF00FF00;
            //this.dgvLayerList.Rows[index].Cells[6].Value = 1;
            //this.dgvLayerList.Rows[index].Cells[7].Value = LineWeight.ByLayer;
            //this.dgvLayerList.Rows[index].Cells[8].Value = 0;
            //this.dgvLayerList.Rows[index].Cells[9].Value = "";
            //this.dgvLayerList.Rows[index].Cells[10].Value = "";
            //this.dgvLayerList.Rows[index].Cells[11].Value = 1;
            //this.dgvLayerList.Rows[index].Cells[12].Value = "";

        }

        private void btnDel_Click(object sender, EventArgs e)
        {
            if (this.dgvLayerList.SelectedRows.Count > 0)
            {
                int index = this.dgvLayerList.SelectedRows.Count;
                for (int i = 0; i < index; i++)
                {
                    LcLayer lcLayer = this.dgvLayerList.SelectedRows[i].DataBoundItem as LcLayer;
                    if (lcLayer.Name == "0" || lcLayer.Name == "Defpoints")
                    {
                        MessageBox.Show("无法删除以下图层：图层0和图层Defpoints");
                        continue;
                    }
                    layerManageAction.lcDocument.Layers.Remove(lcLayer);
                    //dgvLayerList.Rows.RemoveAt(dgvLayerList.SelectedRows[0].Index);
                }
                InitLayers();
                LayerChanged?.Invoke(this, layerManageAction.lcDocument);

            }
        }

        private void dgvLayerList_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex > -1 && e.ColumnIndex > -1)
            {
                if (dgvLayerList.Columns[e.ColumnIndex].Name == "IsStatus")
                {
                    foreach (var item in layerManageAction.lcDocument.Layers)
                    {
                        item.IsStatus = false;
                    }
                    dgvLayerList.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = true;
                    InitLayers();
                    LayerChanged?.Invoke(this, layerManageAction.lcDocument);
                    //else
                    //    dgvLayerList.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = false;
                }
            }
        }

        private void dgvLayerList_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex > -1 && e.ColumnIndex > -1)
            {
                if (dgvLayerList.Columns[e.ColumnIndex].Name == "name")
                {
                    var item = dgvLayerList.Rows[e.RowIndex].DataBoundItem as LcLayer;
                    foreach (var element in this.layerManageAction.vportRt.ActiveElementSet.Elements)
                    {
                        if (element.GetLayerValue().Id == item.Id)
                            element.Layer = dgvLayerList.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
                    }

                }
                LayerChanged?.Invoke(this, layerManageAction.lcDocument);
            }
        }

        private void dgvLayerList_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.ColumnIndex < 0 || e.RowIndex < 0)
                return;
            var lcLayer = dgvLayerList.Rows[e.RowIndex].DataBoundItem as LcLayer;
            if (lcLayer == null)
                return;
            if (dgvLayerList.Columns[e.ColumnIndex].HeaderText == "开")
            {
                e.Value = lcLayer.IsOff ? Properties.Resources.LayerClose : Properties.Resources.LayerOpen;
            }
            if (dgvLayerList.Columns[e.ColumnIndex].HeaderText == "冻结")
            {
                e.Value = lcLayer.IsFrozen ? Properties.Resources.LayerFrozen : Properties.Resources.LayerFree;
            }
            if (dgvLayerList.Columns[e.ColumnIndex].HeaderText == "锁定")
            {
                e.Value = lcLayer.IsLocked ? Properties.Resources.LayerLocked : Properties.Resources.LayerUnlock;
            }

        }

        private void btnCurrent_Click(object sender, EventArgs e)
        {
            foreach (DataGridViewRow item in dgvLayerList.Rows)
            {
                item.Cells[0].Value = false;
            }
            dgvLayerList.SelectedRows[0].Cells[0].Value = true;

        }

        private void dgvLayerList_SelectionChanged(object sender, EventArgs e)
        {
            if (dgvLayerList.SelectedRows.Count > 1)
                this.btnCurrent.Enabled = false;
            else
                this.btnCurrent.Enabled = true;
        }
        private void CellEdit_KeyPress(object sender, KeyPressEventArgs e)
        {
        }
        private void Tb_Leave(object sender, EventArgs eventArgs)
        {
            var c = sender as DataGridViewTextBoxEditingControl;
            var layer = dgvLayerList.Rows[c.EditingControlRowIndex].DataBoundItem as LcLayer;
            if (layerManageAction.lcDocument.Layers.Where(x => x.Name == c.Text.ToString()).ToList().Count > 1)
            {
                layer.Name = c.Tag.ToString();
                MessageBox.Show("名称：" + c.Text + "已在使用，您需要输入其他名称");
                return;
            }

        }
        private void dgvLayerList_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            if (e.Control is DataGridViewTextBoxEditingControl tb)
            {
                DataGridView dgv = sender as DataGridView;
                if (dgv.CurrentCell.ColumnIndex > -1 && dgv.Columns[dgv.CurrentCell.ColumnIndex].HeaderText == "名称")
                {
                    if (dgv.CurrentCell.Value.ToString() == "0")
                    {
                        dgv.CurrentCell.ReadOnly = true;
                        tb.ShortcutsEnabled = true;
                        tb.ImeMode = ImeMode.NoControl;
                        MessageBox.Show("无法重命名以下图层：图层0");
                        return;
                    }
                    tb.Tag = dgv.CurrentCell.Value;
                    tb.ShortcutsEnabled = false;
                    tb.ImeMode = ImeMode.Disable;
                    tb.SelectAll();

                    tb.KeyPress -= new KeyPressEventHandler(CellEdit_KeyPress);
                    tb.KeyPress += new KeyPressEventHandler(CellEdit_KeyPress);

                    tb.Leave -= Tb_Leave;
                    tb.Leave += Tb_Leave;
                }
                else
                {
                    tb.ShortcutsEnabled = true;
                    tb.ImeMode = ImeMode.NoControl;
                    tb.SelectAll();
                    tb.KeyPress -= new KeyPressEventHandler(CellEdit_KeyPress);
                }
            }
        }
    }
}
